package com.item.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.Page;
import com.base.dialect.PaginationSupport;
import com.base.util.StringUtil;
import com.item.dao.model.Book;
import com.item.dao.model.BookExample;
import com.item.dao.model.BookExample.Criteria;
import com.item.dao.model.Cart;
import com.item.dao.model.CartKey;
import com.item.daoEx.model.BookEx;
import com.item.daoEx.model.Year;
import com.item.exception.JSONRepUtils;
import com.item.service.BookService;
import com.item.service.BookService.BookCategory;
import com.item.service.CartService;
import com.item.service.OrderItemService;

@Controller
public class BookController {
	@Autowired
	private BookService bookService;
	@Autowired
	private CartService cartService;
	
	@RequestMapping("/listBook")
	@ResponseBody
	public String list(Page param, String userid, Book book, BookCategory bct, Integer isM) throws Exception{
		BookExample example = new BookExample();
		PaginationSupport.setContext(param.getPageStart(), param.getPageSize(), null);
		Criteria criteria = example.createCriteria();

		if(!bct.isEmpty()){
			criteria.andCtCodeLike(bct.getCMCodeForSelect());
		}

		if(StringUtils.isNotBlank(book.getName())){
			criteria.andNameLike("%"+book.getName()+"%");
		}
		if(StringUtils.isNotBlank(book.getAuthor())){
			criteria.andAuthorLike("%"+book.getAuthor()+"%");
		}
		if(StringUtils.isNotBlank(book.getPublisher())){
			criteria.andPublisherLike("%"+book.getPublisher()+"%");
		}
		if(book.getIsHot() != null) {
			criteria.andIsHotGreaterThan(0);
		}
		if(isM == null || isM == 0)
			example.setOrderByClause("is_hot DESC, reportory ASC, time_publish DESC");
		else
			example.setOrderByClause("is_hot DESC, modify_time DESC, time_publish DESC");
		List<Book> list = bookService.selectByExample(example);
		Object objForSer = new Page(PaginationSupport.getContext().getTotalCount(), list);
		if(StringUtils.isNotBlank(userid)) {
			List<BookEx> listEx = new ArrayList<BookEx>();
			for(Book b : list) {
				BookEx ex = new BookEx(b);
				CartKey key = new CartKey();
				key.setBookid(b.getId());
				key.setUserid(userid);
				Cart cart = cartService.selectByPrimaryKey(key);
				if(cart != null) {
					ex.setIsInCart(1);
				}
				listEx.add(ex);
			}
			objForSer = new Page(PaginationSupport.getContext().getTotalCount(), listEx);
		}
		
		return JSONRepUtils.serialize(objForSer, isM);
	}
	
	@RequestMapping("/showSortByOrder")
	public String sortByOrder() {
		return "book/bookListOrder";
	}
	
	@RequestMapping("/sortByOrder")
	@ResponseBody
	public String sortOrder(Page param, Integer isM) {
		Object objForSer = null;
		
		PaginationSupport.setContext(param.getPageStart(), param.getPageSize(), null);
		List<BookEx> list = bookService.selectBookByOrder();
		objForSer = new Page(PaginationSupport.getContext().getTotalCount(), list);
		
		return JSONRepUtils.serialize(objForSer, isM);
	}
	
	@RequestMapping("/listBookCategory")
	@ResponseBody
	public String findByIdBookCategory(String id, Integer isM, HttpSession session)throws Exception{		
		Book n = bookService.selectByPrimaryKey(id);
		BookEx ex = new BookEx(n);
		ex.setCtCodes();
		bookService.fillCateInfo(ex);
		List<BookCategory> bcts = ex.getCtCodeList();
		return JSONRepUtils.serialize(bcts, isM);
	}
	
	@RequestMapping("/showlistBook")
	public String list() {
		return "book/bookList";
	}
	
	@RequestMapping("/year")
	@ResponseBody
	public String year() {		
		return JSONRepUtils.serialize(Year.listYear(), 0);
	}
	
	@RequestMapping("/toEditBook")
	public String toEdit()throws Exception{
		return "book/bookEdit";
	}
	
	@RequestMapping(value="/saveBook",method=RequestMethod.POST)
	@ResponseBody
	public String save(Book book, BookCategory bct, HttpSession session)throws Exception{		
		try{
			if(StringUtil.isEmpty(book.getId())){
				book.setName(book.getName() + " " + book.getAuthor() + "著");
				book.setCreateTime(new Date());
//				book.setCtCode(bookService.getCMCodeForInsert(bct));
				bookService.insertSelective(book);
			} else {
				book.setModifyTime(new Date());
//				book.setCtCode(bookService.getCMCodeForInsert(bct));
				bookService.updateByPrimaryKeySelective(book);
			}
		}catch(Exception e){
			e.printStackTrace();
			return "{\"success\":false}";
		}
		
		return "{\"success\":true}";
	}
	
	@RequestMapping(value="/findByIdBook")
	@ResponseBody
	public String findById(String id, String userid, Integer isM, HttpSession session)throws Exception{
		Book n = bookService.selectByPrimaryKey(id);
		BookEx ex = new BookEx(n);
		ex.setCtCodes();
		bookService.fillCateInfo(ex);
		if(StringUtils.isNotBlank(userid)) {//查看该本书是否已在购物车中
			CartKey key = new CartKey();
			key.setBookid(id);
			key.setUserid(userid);
			Cart cart = cartService.selectByPrimaryKey(key);
			if(cart != null) {
				ex.setIsInCart(1);
			}
		}
		
		return JSONRepUtils.serialize(ex, isM);
	}
	
	@RequestMapping("/delBook")
	@ResponseBody
	public String del(String id,String url,HttpSession session)throws Exception{
		String[] ids = id.split(",");
		int len = ids.length;
		for(int i = 0; i < len; i++) {
			bookService.deleteByPrimaryKey(ids[i]);
		}
		return "{\"success\":true}";
	}
	
	@RequestMapping("/setHot")
	@ResponseBody
	public String setHot(Book book) {
		book.setModifyTime(new Date());
		bookService.updateByPrimaryKeySelective(book);
		return "{\"success\":true}";
	}
}

